<template>
  <div class="data-table" >
    <div class="btn-fix">
      <el-upload ref="upload"
        multiple
        class="upload-demo"
        action="/springBoot/file-service/io/upload"
        :show-file-list="false"
        :limit="limit"
        :on-exceed="handleExceed"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <el-button size="default" type="primary">点击上传</el-button>
      </el-upload>
    </div>
    <div class="data-page"
      v-loading.fullscreen.lock="loading"
      :element-loading-text="loadingText"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.6)"> 
      <div class="img-box" v-for="(item, index) in tableData" :key="index"
        :class="item.is_delete == -1 ? 'error' : ''" :title="item.file_name">
        <template v-if="fileTypeList.includes(item.file_type.substring(1))">
          <el-image :key="index" :src="item.url_thumbnail" :lazy="true"
            :preview-src-list="SELECT_IOList(index)">
          </el-image>
        </template>
        <template v-else>
          <el-image :src="require('@/assets/images/download.png')" ></el-image>
        </template>
        
        <div class="error" v-if="item.is_delete == -1">已删除</div>
        <div class="error" v-if="item.ip == '127.0.0.1'" :class="item.is_delete == 0 ? 'dev' : 'dev-delete'">开发环境</div>
        <div class="tool">
          <i class="el-icon-picture-outline" title="原图预览" @click="handle('preview', item)"></i>
          <i class="el-icon-download" title="原图下载" @click="handle('download', item)"></i>
          <i class="el-icon-close" v-if="item.is_delete == 0" title="删除" @click="handle('delete', item)"></i>
          <i class="el-icon-refresh-left" v-if="item.is_delete == -1" title="撤销删除" @click="handle('revokeDelete', item)"></i>
        </div>

        <div class="info">
          <div>名称：{{item.name}}</div>
          <div>大小：{{item.file_size}}</div>
          <div>{{item.create_time}}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
// import { SELECT_IO, DELETE_IO, REVOKE_DELETE_IO } from '@/plugins/api/common';
export default Vue.extend({
  name: "ui",
  data() {
    return {
      form: {
        is_delete: false
      },
      tableData: [],
      loading: false,
			loadingText: 'Loading...',
      page: {
        current: 1,
        pageSizes: [10, 20, 30, 40, 50, 100],
        pageSize: 24,
        total: 0
      },
      finished: false,
      srcList: [],
      fileTypeList: ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'ico', 'jfif'],
      dialog: {
        visible: false,
      },
      limit: 32,
      selectedNum: 0,
      uploadedNum: 1,
      throttleTimer: null
    };
	},
  mounted() {
    this.loadData();
    document.title = "文件服务";
    const page = document.getElementsByClassName('data-page')[0];
    if (this.isDaytime()) {
      page.style.backgroundColor = 'white';
    } else {
      page.style.backgroundColor = 'black';
    }
    window.addEventListener('scroll', this.handleScroll);
  },
  methods: {
    isDaytime() {
      // 获取当前时间
      var now = new Date();
      
      // 假设这是你已知的日出和日落时间，这里简化为常量
      var sunrise = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 6, 0, 0); // 假设日出时间为早上6点
      var sunset = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0, 0); // 假设日落时间为下午6点
      
      // 检查当前时间是否在日出和日落之间
      return now >= sunrise && now <= sunset;
    },

    // 页面滚动加载数据
    handleScroll() {
      if (this.finished) {
        this.loading = false;
        return;
      }
      const scrollH = document.documentElement.scrollHeight;// 文档的完整高度
      const scrollT = document.documentElement.scrollTop || document.body.scrollTop; // 当前滚动条的垂直偏移
      const screenH = window.screen.height;  // 屏幕可视高度
      if ((scrollH - scrollT - screenH) < 5) { // 5 只是一个相对值，可以让页面再接近底面的时候就开始请求
          this.loading = true;
          // document.body.style.overflow = 'hidden';
          this.throttleTimer = setTimeout(() => {
          if (!this.throttleTimer) return;
          // 执行请求
          this.page.current++;
          this.loadData();
          // document.body.style.overflow = 'auto';
          // 加载数据
          this.throttleTimer = null;
        }, 1000)
      }
    },

    SELECT_IOList(index) {
      let arr = []
      let i = 0;
      for(i;i < this.srcList.length;i++){
        arr.push(this.srcList[i+index])
        if(i+index >= this.srcList.length-1){
          index = 0-(i+1);
        }
      }
      return arr;
    },

    async handle (type, obj) {
      if (type === 'preview') {
        window.open(obj.url);
      }
      if (type === 'download') {
        window.open(obj.url + '?type=d');
      }
      if (type === 'is_delete') {
        this.page.current = 1;
        this.is_delete = obj;
        this.loadData();
      }
      if (type === 'revokeDelete') {
        const res = await REVOKE_DELETE_IO({id: obj.id});
        if (res.status) {
          this.$message({
            type: 'success',
            message: '撤销成功!'
          });
          this.loadData();
        } else {
          this.$message({
            type: 'error',
            message: res.messages || '撤销失败!'
          });
        }
        this.loadData();
      }
      if (type === 'delete') {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          DELETE_IO({id: obj.id}).then(res => {
            if (res.status) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.loadData();
            } else {
              this.$message({
                type: 'error',
                message: res.messages || '删除失败!'
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    },

    formatFileSize(bytes) {
      var result = null;
      bytes = +bytes;
      if (bytes === 0) return '0 B';
      
      var k = 1024;
      
      const sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      
      let i = Math.floor(Math.log(bytes) / Math.log(k));

      var num = bytes / Math.pow(k, i);
      return num.toPrecision(3) + ' ' + sizes[i];
      
      //return (bytes / Math.pow(k, i)) + ' ' + sizes[i]; 
      //toPrecision(3) 后面保留一位小数，如1.0GB //return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
      return result;
    },

    /**
     * 查询
     */
    query() {
      this.page.current = 1;
      this.loadData();
    },

    /**
     * 重置
     */
    reset() {
      this.form.is_delete = false;
      this.loadData();
    },

    // 查看
    preview(map) {
      this.$utils.el.alert(map.userAgent);
    },

    /**
     * 加载数据
     */
    loadData() {
      if (this.finished) return;
      this.loading = true;
			this.loadingText = 'Loading...';
      SELECT_IO({
        needPage: true,
        current: this.page.current,
        pageSize: this.page.pageSize,
        label: 'image',

        queryData: {
          name: 333,
          age: undefined
        },
      }).then(response => {
        this.loading = false;
        if (!response.data.rows.length) {
          this.finished = true;
          return;
        }
        this.srcList = [];
        response.data.rows.forEach(item => {
         
          item.file_size = this.formatFileSize(item.file_size_thumbnail);
        });
        this.tableData = [...this.tableData, ...response.data.rows];

        this.tableData.forEach(item => {
           this.srcList.push(item.url_preview);
        });

        this.page.total = response.data.total;
      });
    },

    /**
     * 每页多少条
     */
    handleSizeChange(val) {
      this.page.current = 1;
      this.page.pageSize = val;
      this.loadData();
    },

    /**
     * 下一页
     */
    handleCurrentChange(val) {
      this.page.current = val;
      this.loadData();
    },
    handleExceed(files, fileList) {
      alert(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件`);
      this.$refs.upload.clearFiles();
    },  
    handleAvatarSuccess(res, file) {
      this.uploadedNum++;
			this.loading = false;
      if (res.status) {
        this.selectedNum = 0;
        this.uploadedNum = 1;
        alert('上传成功');
        this.$refs.upload.clearFiles();

        this.page.current = 1;
        this.tableData = [];
        this.loadData();

        window.scrollTo(0, 0);
      } else {
         this.$message.error(res.messages || '上失败');
         this.$refs.upload.clearFiles();
      }
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      this.selectedNum++;
      // alert(JSON.stringify(file))
			this.loadingText = '正在上传，请稍后。。。';
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 10;
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
			
			this.loading = isLt2M ? true : false;
      return isLt2M;
      return isJPG && isLt2M;
    }
  }
});
</script>

<style lang="less" scoped>
  html, body {
    background: black;
  }
  .btn-fix {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 99;
    padding: 10px;
    background: rgba(0, 0, 0, .6);
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    .upload-demo {
      /deep/ .el-upload {
        display: block;
        width: 100%;
        background-image:linear-gradient(-225deg,#FF057C 0%, #7C64D5 48%, #4CC3FF 100%);
      border-radius: 8px;

      }
      width: 100%;
    }
    .el-button {
      display: block;
      width: 100%;
      border-radius: 8px;
      padding: 15px 0;
      font-size: 16px;
      border-color: transparent !important;
      background:transparent !important;
    }
  }.data-table {
    height: 100vh;
    padding-bottom: 50px;
    // background: black;
    // background-image:linear-gradient(-225deg,#FF057C 0%, #7C64D5 48%, #4CC3FF 100%)
  }
	.data-page {
    display: flex;
    flex-wrap: wrap;
		overflow: auto;
    margin-bottom: 30px;
	}
	/deep/ .el-icon-loading {
		font-size: 32px;
	}
  .img-box {
    position: relative;
    display: flex;
		overflow: hidden;
		width: 33.33%;
		// height: 150px;
    height: 22vh;
		border-radius: 0;
    padding-right: 2px;
    padding-top: 2px;
    &:nth-child(3n) {
      padding-right: 0;
    }
    // background: red;
		/deep/ .el-image {
      display: flex;
      justify-content: center;
      align-items: center;
			width: 150px;
      // height: 150px;
      height: 100%;
      img {
        max-width: 125%;
        max-height: 100%;
        width: auto;
        height: auto;
        cursor: pointer;
        transform: scale(1.7);
      }
		}
    &.error {
      .el-image {
        border: 2px solid red !important;
				border-radius: 5px;
      }
    }
    .error {
      position: absolute;
      top: 0;
      left: 0;
      background: rgba(255, 0, 0, .7);
      color: white;
      padding: 2px 5px;
      border-top-left-radius: 5px;
      &.dev {
        top: 0;
        background: blue;
        .el-image {
          border-color: blue;
        }
      }
      &.dev-delete {
        top: 25px;
        background: blue;
      }
    }
    .tool {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 15px;
      background: black;
      opacity: 0;
      color: white;
      padding: 2.5px 5px;
			transform: translateY(-10px);
      transition-duration: .5s;
      i {
        cursor: pointer;
        padding: 0 2px;
        &:hover {
          color: red;
        }
      }
    }
    .info {
      opacity: 0;
      position: absolute;
      bottom: 0;
      left: 0;
      background: rgba(0, 0, 0, .7);
      color: white;
			font-size: 12px;
      padding: 2.5px 5px 5px 5px;
      width: calc(100%);
      transition-duration: .5s;
      transform: translateY(10px);
      div {
        padding-top: 2.5px;
      }
    }

    &:hover1 {
			background: #E5F3FF;
      .tool {
        opacity: 1;
				transform: translateY(0);
        transition-duration: .5s;
      }
      .info {
        opacity: 1;
        transform: translateY(0);
        transition-duration: .5s;
      }
    }
  }
</style>